/**
 * 数据源
 * 支持列表数据源的加载和各种列表的操作
 */
Rap.define('/ly/utils/dataStore.js', [], function () {
    var DataSourceParamStore = {};
    return function (config) {
        if (typeof(config) == 'string') {
            config = {url: config, transform: null};
        }
        var base = "";
        if (config.url) {
            base = config.url.substring(0, config.url.lastIndexOf('/') + 1);
        }
        function fixurl(url) {
            if (url.indexOf('/') == 0) {
                return url;
            }
            return base + url;
        }

        var params = {
            step: 20,
            page: 1
        };
        params = _.extend(params, config.params);
        if (config.name) {
            var oldParams = DataSourceParamStore[config.name];
            if (oldParams) {
                params = oldParams;
            } else {
                DataSourceParamStore[config.name] = params;
            }
        }
        var selectionChange=[];
        var timeout_index = 0;
        return {
            data: [],
            page_sizes: [10,20, 40, 100],
            pk: config.pk ? config.pk : 'id',
            loading: false,
            isReset: false,
            total: config.total ? config.total : 0,
            params: params,
            config: config,
            selection: [],
            extra_data:[],
            method:params.method?params.method:'get',
            isIndeterminate:false,
            reset: function () {
                var that = this;
                this.isReset = true;
                setTimeout(function() {
                    that.isReset = false;
                }, 300);
                this.params = _.extend({
                    step: this.params.step,
                    page: 1
                }, { 'status': this.params.status });
            },
            onSelectionChange:function (call) {
                selectionChange.push(call);
            },
            load:function (page){
                if(timeout_index){
                    clearTimeout(timeout_index);
                }
                var me=this;
                timeout_index=setTimeout(function (){
                    timeout_index=0;
                    me._load(page);
                },50);
            },
            _load: function (page) {

                // 重置操作不重新加载列表
                if (this.isReset) {
                    return;
                }
                if (page) {
                    this.params.page = page;
                }
                var me = this;
                this.loading = true;
                this.selection.length=0;
                this.isIndeterminate=false;
                if (config.data) {
                    var p = Rap.promise();
                    setTimeout(function () {
                        me.loading = false;
                        var data = config.data;
                        if (typeof(config.data) == 'function') {
                            data = config.data();
                        }
                        me.data.length = 0;
                        data.forEach(function (element) {
                            me.data.push(element);
                        });
                        me.total = me.data.length * (parseInt(Math.random() * 3) + 1);
                        p.resolve();
                    }, 300);
                } else {
                    me.data.splice(0);
                    me.data.length = 0;
                    var axios_config={
                        responseType: 'json',

                        loading_bar: true,
                        transformResponse: function (data) {
                            if (config.transform) {
                                data = config.transform(data);
                            }
                            return data;
                        }
                    };
                    var p=null;
                    if(this.method==='get'){
                        axios_config.params = me.params;
                        p=axios.get(config.url, axios_config);
                    }else{
                       p=axios.post(config.url,me.params,axios_config )
                    }
                    p.then(function (response) {
                        me.loading = false;
                        var result = response.data;
                        var data = result;
                        if (!(result instanceof Array)) {
                            if(_.has(result,'data')){
                                data = result.data;
                            }else if(_.has(result,'list')){
                                data = result.list;
                            }
                            if(_.has(result,'total')){
                                me.total = result.total;
                            }else if(_.has(result,'count')){
                                me.total = result.count;
                            }
                            if(_.has(result,'extra_data')){
                                me.extra_data = result.extra_data;
                            }
                        }
                        me.data.splice(0);
                        _.each(data, function (item) {
                            me.data.push(item);
                        });

                    }).catch(function (error) {
                        me.loading = false;
                        console.log(error);
                    }).then(function () {

                    });
                }
            }, sizeChange: function (step) {
                this.params.step = step;
                this.load();
            }, select: function (val) {
                this.selection = val;
            }, onItemCheckChange: function () {
                this.selection = _.where(this.data, {__checked: true});
                _.each(selectionChange,function (call) {
                    call();
                });

            },
            delete: function (msg, action, row, params, load) {
                action = fixurl(action);
                var me = this;
                var p = Rap.promise().resolve();
                if (msg) {
                    p = App.$confirm(msg, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    });
                }
                p.then(function () {
                    me.loading = true;
                    if (!params) {
                        params = {};
                    }
                    params[me.pk] = row[me.pk];
                    axios.post(action, params).then(function (rs) {
                        if (rs.data.success) {
                            me.loading = false;
                            if (load) {
                                me.load(1);
                            } else {
                                me.data.remove(row);
                            }
                            if (!rs.data.msg) {
                                rs.data.msg = '操作成功';
                            }
                            App.$message({
                                type: 'success',
                                message: rs.data.msg
                            });
                        } else {
                            App.$message({
                                type: 'error',
                                message: rs.data.msg
                            });
                            me.load(1);
                        }
                    }).catch(function () {
                        me.loading = false;
                    });
                }).catch(function () {

                });
            },
            do: function (msg, action, row, params, load) {
                action = fixurl(action);
                var me = this;
                var p = Rap.promise().resolve();
                if (msg) {
                    p = App.$confirm(msg, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    });
                }
                p.then(function () {
                    me.loading = true;
                    if (!params) {
                        params = row;
                    }
                    params[me.pk] = row[me.pk];
                    axios.post(action, params).then(function (rs) {
                        me.loading = false;
                        if (!load && row) {
                            _.extend(row, params);
                            if (rs.data.data) {
                                _.each(rs.data.data, function (v, k) {
                                    if (v != null) {
                                        row[k] = v;
                                    }
                                });

                            }
                        } else {
                            me.load();
                        }
                    }).catch(function () {
                        me.loading = false;
                    });
                }).catch(function () {

                });
            }, input: function (msg, action, name, row, params, def, load) {
                action = fixurl(action);

                var me = this;
                App.$prompt(msg, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputPlaceholder: typeof(def)=='number'?"请输入数值":"请输入内容",
                    inputType:typeof(def)=='number'?'number':'textarea',
                    inputValue: def
                }).then(function (what) {
                    if (!params) {
                        params = row;
                    }
                    params[name] = what.value;
                    params[me.pk] = row[me.pk];
                    axios.post(action, params).then(function () {
                        if (!load && row) {
                            _.extend(row, params);
                        } else {
                            me.load(1);
                        }
                        App.$message({
                            type: 'success',
                            message: '修改成功!'
                        });
                    });
                }).catch(function () {
                });
            }, allDo: function (msg, action, params) {
                action = fixurl(action);
                var me = this;
                var selection = this.selection;
                if (selection.length == 0) {
                    App.$message('请先选择');
                    return;
                }
                var ids = _.pluck(selection, this.pk);
                if (!params) {
                    params = {}
                }
                params.ids = ids;
                var p = Rap.promise().resolve();
                if (msg) {
                    p = App.$confirm(msg, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    });
                }
                p.then(function () {
                    axios.post(action, params).then(function () {
                        me.load(1);
                        App.$message({
                            type: 'success',
                            message: '操作成功!'
                        });
                    });
                }).catch(function () {

                });
            }, search: function (key) {
                if (!key)key = 'search';
                var me = this;
                return function (value) {
                    me.params[key] = value;
                    me.load(1);
                }
            }, sort: function (sort) {
                if (!sort.order) {
                    this.params.sort = '';
                } else if (sort.order == 'ascending') {
                    this.params.sort = sort.prop + ' asc';
                } else {
                    this.params.sort = sort.prop + ' desc';
                }
                this.load(1);
            },
            //更新表中任意字段(column)的值为value
            update: function (msg, action, id, column, value) {

                action = fixurl(action);
                var me = this;
                var p = Rap.promise().resolve();
                if (msg) {
                    p = App.$confirm(msg, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    })
                }
                p.then(function () {
                    axios.post(action, {id: id, column: column, value: value}).then(function (rs) {
                        if (rs.data.success) {
                            me.load();
                            App.$message({
                                type: 'success',
                                message: '操作成功!'
                            });
                        } else {
                            App.$message({
                                type: 'error',
                                message: rs.msg
                            });
                        }

                    });
                }).catch(function () {

                });
            }
        }
    };
});
